<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen v-model="showDialog" :title="title">
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-deptName>
                <el-input
                  v-if="isSpecialEdit === 1"
                  v-model="formInfo.data.deptName"
                  disabled
                ></el-input>
                <el-input
                  v-else
                  v-model="formInfo.data.deptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
            <div class="model-tips">
              (证照：<span>近效期</span>
              <span class="model-tips-nearly"></span>
            </div>
            <div class="model-tips">
              <span>过期</span>
              <span class="model-tips-expire"></span>)
            </div>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :check-box="false"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <el-form-item class="margin-bottom">
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item ss">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: ['blur', 'change'],
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="99999999"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-item ww"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="scope.row.unitConvertCoefficient - 1"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                  <template v-slot:col-price="scope">
                    <p>{{ scope.row.price }}</p>
                    <p
                      style="color: red"
                      v-if="
                        scope.row.isLimitPrice == 1 &&
                        scope.row.price > scope.row.purchaseLimitPrice
                      "
                    >
                      超过产品限价:{{ scope.row.purchaseLimitPrice }}
                    </p>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
  </div>
</template>

<script setup name="purchApplicationModify">
import {
  createPurchApplication,
  updatePurchApplication,
  submitPurchApplication,
} from '@/api/purch'
import { getCoreSystemConfigGetConfigValue } from '@/api/core.js'
import { getCustomizeSetting } from '@/api/customize'
import { purchApplicationDetailByProductIds } from '@/api/warning'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps([
  'visible',
  'title',
  'isSpecialEdit',
  'productIds',
  'checkData',
])

const formRefs = []
const formInfo = ref({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    createUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
  },
  fieldList: [
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    { label: '部门', value: 'deptName', type: 'slot' },
    {
      label: '是否临采',
      value: 'temporaryPurch',
      type: 'select-model',
      code: 'default_no_or_yes',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
  },
  labelWidth: '120px',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: purchApplicationDetailByProductIds,
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: deleteProduct,
        show: true,
      },
    ],
  },
})
const deptInfo = ref({
  visible: false,
  checkBox: false,
  query: {
    deptAuth: 'id',
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    queryMap: {},
    queryParams: {
      deptId: null,
    },
  },
})
const tableKey = ref(
  'purchApplicationDetailModify-com.slip.spd.entity.vo.purch.PurchApplicationDetailVO'
)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const licencesSystemConfig = ref(undefined)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  getValueList()
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

setData()
function setData() {
  let obj = {
    qty: {
      label: '申购数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchApplication:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchApplication:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('purchApplication:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      getList()
    }
  })
}
//获取申购单明细
function getList() {
  let productIds = []
  if (props.checkData && props.checkData.length) {
    //【库存查询/部门产品库存查询】生成申购单
    productIds = props.checkData
  } else {
    props.productIds.map((row) => row.productId)
  }
  let params = {
    productIds: productIds,
  }
  purchApplicationDetailByProductIds(params).then((resp) => {
    if (resp && resp.success) {
      resp.data.forEach((val) => {
        val.id = null
        val.orderId = null
        val.prePurchQty = null
        val.prePurchCalcQty = null
        val.actualPurchQty = null
        val.actualPurchCalcQty = null
        if (props.productIds) {
          props.productIds.forEach((item) => {
            if (item.productId === val.productId) {
              val.qty = proxy.$fn.Subtr(item.lowLevel || 0, item.qty || 0)
              val.calcQty = proxy.$fn.accMul(
                val.qty,
                val.unitConvertCoefficient || 0
              )
              val.largeUnitQty = proxy.$fn.accDiv(
                proxy.$fn.Subtr(val.calcQty, val.smallUnitQty || 0),
                val.unitConvertCoefficient || 0
              )
            }
          })
        }
      })
      if (props.checkData && props.checkData.length) {
        //【库存查询/部门产品库存查询】生成申购单
        tableInfo.value.data = resp.data
      } else {
        tableInfo.value.data = resp.data.filter((item) => item.qty > 0)
      }

      formInfo.value.data.id = null
    }
  })
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      licencesSystemConfig.value = resp.data
    }
  })
}
//删除产品
function deleteProduct(data = undefined) {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.data = tableInfo.value.data.filter((row) => data !== row)
    })
}
function save(eventObj, isSubmit, ids = undefined) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data.map((item) => {
      let smallUnitQty = parseFloat(item.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(item.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(item.largeUnitQty || 0)

      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      item.qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      item.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(item.price)
      )
      return {
        ...item,
        calcQty: calcQty,
      }
    })
    const data = formInfo.value.data
    data.isSpecialEdit = props.isSpecialEdit
    data.mergeDetails = details
    const api = data.id ? updatePurchApplication : createPurchApplication
    api(data).then((resp) => {
      if (resp && resp.success) {
        if (isSubmit) {
          submitPurchApplication(ids).then((resp) => {
            if (resp.success) {
              tableInfo.value.refresh = Math.random()
              showDialog.value = false
              // emits("returnModify", false);
              proxy.$router.push('/purch/application')
            }
          })
        } else {
          showDialog.value = false
          // emits("returnModify", false);
          proxy.$router.push('/purch/application')
        }
      }
    })
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
